package name.fowler.refactoring.simplestore.persistence;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import name.fowler.refactoring.simplestore.domain.Movie;

public class MovieRepository {
	@PersistenceUnit
	private EntityManagerFactory entityManagerFactory;
	
	public MovieRepository() {};
	
	// This constructor is for testing only
	public MovieRepository(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}
	
	public void addMovie(Movie m) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.persist(m);
        entityManager.getTransaction().commit();
	}
	
	public void removeMovie(Movie m) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.remove(m);
        entityManager.getTransaction().commit();
	}
	
	public void updateMovie(Movie m) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
        entityManager.merge(m);
        entityManager.getTransaction().commit();
	}
	
	public List<Movie> queryAll() {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<Movie> Movies = entityManager
				.createNamedQuery("Movie.findAll", Movie.class)
				.getResultList();
		entityManager.close();
		return Movies;
	}
	
	public List<Movie> getByName(String title) {
		EntityManager entityManager = entityManagerFactory.createEntityManager();
		List<Movie> Movies = entityManager
				.createNamedQuery("Movie.findByTitle", Movie.class)
				.setParameter("title", title)
				.getResultList();
		entityManager.close();
		return Movies;
	}
}
